package com.mocoop.task;

import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.os.AsyncTask;
import android.util.Log;

import com.mocoop.biz.SyncDataBiz.SyncDataCallBack;
import com.mocoop.dao.SyncDaoImp;

public class SaveDataTask extends AsyncTask<Object, Void, Void> {

	private SyncDataCallBack syncDataCallBack;

	public SyncDataCallBack getSyncDataCallBack() {
		return syncDataCallBack;
	}

	public void setSyncDataCallBack(SyncDataCallBack syncDataCallBack) {
		this.syncDataCallBack = syncDataCallBack;
	}

	@Override
	protected Void doInBackground(Object... objects) {
		try {
			JSONObject response = (JSONObject) objects[0];
			SyncDaoImp syncDao = (SyncDaoImp) objects[1];
			String tableName = objects[2].toString();
			JSONArray jsonArray = response.getJSONArray("recordset");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject obj = jsonArray.getJSONObject(i);

				ContentValues cv = new ContentValues();
				Iterator<String> it = obj.keys();
				while (it.hasNext()) {
					String key = it.next();
					try {
						cv.put(key, obj.getString(key));
					} catch (Exception e) {
						if (obj.get(key) instanceof Integer) {
							cv.put(key, obj.getInt(key));
						} else if (obj.get(key) instanceof Long) {
							cv.put(key, obj.getLong(key));
						}
					}

				}
				Log.d("Test", tableName);
				syncDao.addData(cv, tableName);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		if (syncDataCallBack != null) {
			syncDataCallBack.onSuccess(1);
		}
		return null;
	}

}
